package com.ken.mqbase.dlx;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列 消费者
 * Created by renchongyu on 2018/11/19.
 */
public class ConsumerDlx {

    public static void main(String[] args) throws Exception{
        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();
        //正常的交换机、key键、队列名
        String exchange = "test_dlx_exchange";
        String routingKey = "dlx.#";
        String queueName = "test_dlx_queue";

        //死信的交换机、队列名。之所以没有用key键，是因为通常都是#通配的
        String dlxExchange = "dlx.exchange";
        String dlxQueue = "dlx.queue";

        /**
         * 这里要建立两个交换机、声明两个队列、响应绑定关系。一个是正常队列，一个就是死信队列。
         * 值得注意的是，死信一定要绑在正常队列的agruments(Map)属性上.
         */
        //1.正常队列：创建交换机、声明队列、绑定关系
        channel.exchangeDeclare(exchange,"topic",true,false,null);
        //这个Map就是用法放死信交换机名词的
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("x-dead-letter-exchange",dlxExchange);
        channel.queueDeclare(queueName,true,false,false,map);
        channel.queueBind(queueName,exchange,routingKey);

        //2.死信队列：创建交换机、声明队列、绑定关系
        channel.exchangeDeclare(dlxExchange,"topic",true,false,null);
        channel.queueDeclare(dlxQueue,true,false,false,null);
        channel.queueBind(dlxQueue,dlxExchange,"#");

        channel.basicConsume(queueName,true,new MyDlxConsumer(channel));

    }
}
